import 'package:permission_handler/permission_handler.dart';
import 'package:todo_app/components/Overlay/main.dart';
import 'package:todo_app/utils/SharedPreferencesUtil.dart';
import 'package:manage_calendar_events/manage_calendar_events.dart';

class AlarmClock {

  static final calendarPlugin = CalendarPlugin();

  static Future<Calendar?> getCalendar() async {
    var status = await Permission.calendar.request();
    if(status.isDenied || status.isPermanentlyDenied) return null;
    var hasPermission = await calendarPlugin.hasPermissions();
    if(hasPermission == true) {
      var calendarList = await calendarPlugin.getCalendars();
      return calendarList?.first;
    }
    return null;
  }

  static set(DateTime time,int alertId, {
    String? title,
    String? description
  }) async {
    var calander = await getCalendar();
    if(calander == null) return;
    var eventId = await calendarPlugin.createEvent(
      calendarId: calander.id!, 
      event: CalendarEvent(
        startDate: time,
        endDate: time.add(const Duration(seconds: 10)),
        hasAlarm: true,
        title: title,
        description: description,
        attendees: Attendees(attendees: []),
        reminder: Reminder(minutes: 0)
      )
    );
    if(eventId != null) {
      showOverlayToast("闹钟设置成功");
      SharedPreferenceUtil.setBool("AlarmClock:$alertId", true);
      SharedPreferenceUtil.setString("AlarmClockEvent:$alertId", eventId);
      SharedPreferenceUtil.setInt("AlarmClockTime:$alertId", time.millisecondsSinceEpoch);
    }
  }

  static cancel(int alertId) async {
    var eventId = SharedPreferenceUtil.getString("AlarmClockEvent:$alertId", defValue: '');
    var calander = await getCalendar();
    if(calander == null) return;
    var success = await calendarPlugin.deleteEvent(calendarId: calander.id!, eventId: eventId);
    if(success == true) {
      SharedPreferenceUtil.setBool("AlarmClock:$alertId", false);
      SharedPreferenceUtil.setInt("AlarmClockTime:$alertId", -1);
      SharedPreferenceUtil.setString("AlarmClockEvent:$alertId", "");
      showOverlayToast("闹钟已取消");
    }
  }

  static exist(int alertId) {
    var eventId = SharedPreferenceUtil.getString("AlarmClockEvent:$alertId", defValue: '');
    if(eventId == '') return false;
    return SharedPreferenceUtil.getBool("AlarmClock:$alertId");
  }
}